package com.zys.hotel_management.service.impl;


import com.zys.hotel_management.entity.Booking;
import com.zys.hotel_management.entity.Room;
import com.zys.hotel_management.mapper.BookingMapper;
import com.zys.hotel_management.service.BookingService;
import com.zys.hotel_management.service.RoomService;
import com.zys.hotel_management.utils.UserContext;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class BookingServiceImpl implements BookingService {
    @Resource
    private BookingMapper bookingMapper;
    @Resource
    private RoomService roomService;

    @Transactional
    @Override
    public void createBooking(Booking booking) {
        booking.setBookingTime(new Date());
        booking.setCustomerId(UserContext.getUser().getCustomerId());
        booking.setStatus("预订中");
        bookingMapper.insert(booking);
        Room room = new Room();
        room.setRoomId(booking.getRoomId());
        room.setStatus("已预订");
        roomService.updateRoom(room);
    }

    @Override
    public List<Booking> getBookingsByCustomer() {
        Integer customerId = UserContext.getUser().getCustomerId();
        return bookingMapper.findByCustomerId(customerId);
    }

    @Override
    public List<Booking> getAllBookings() {
        return bookingMapper.findAll();
    }

    @Override
    public Booking getBookingById(Integer bookingId) {
        return bookingMapper.findById(bookingId);
    }

    @Override
    public void cancelBooking(Integer bookingId) {
        Booking booking = bookingMapper.findById(bookingId);
        if (booking == null) {
            throw new RuntimeException("预订不存在");
        }
        Room room = new Room();
        room.setRoomId(booking.getRoomId());
        room.setStatus("空闲");
        roomService.updateRoom(room);
        bookingMapper.cancelBooking(bookingId);
    }
}